import os
import sys
import time
import ctypes
import tkinter as tk
from tkinter import messagebox
import subprocess
import threading
from PIL import Image, ImageDraw
import pystray
from filelock import FileLock, Timeout


# pyinstaller -F -w --add-data "壁纸;壁纸" --add-data "图标/favicon.ico;图标" --icon=图标/favicon.ico --name="Windows壁纸设置程序 - 黄朝勋" Windows壁纸设置程序.py
def set_wallpaper(image_path):
    try:
        SPI_SETDESKWALLPAPER = 20
        path = ctypes.create_unicode_buffer(image_path)
        result = ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path, 3)
        if not result:
            raise Exception("Failed to set wallpaper")
    except Exception as e:
        print(f"Error setting wallpaper: {e}")


def open_wallpaper_folder():
    global wallpaper_folder
    wallpaper_folder_abs = os.path.abspath(wallpaper_folder)
    if os.path.isdir(wallpaper_folder_abs):
        try:
            subprocess.run(['explorer', wallpaper_folder_abs], check=True)
        except subprocess.CalledProcessError as e:
            print(f"打开文件夹时出错: {e}")
    else:
        print(f"壁纸文件夹 '{wallpaper_folder_abs}' 不存在")


def quit_program():
    root = tk.Tk()
    root.title("退出程序 作者：黄朝勋")
    root.geometry("300x150")
    root.attributes('-alpha', 0.85)
    root.configure(bg='#add8e6')

    try:
        root.iconbitmap(resource_path('图标/favicon.ico'))
    except Exception as e:
        print(f"设置图标时出错: {e}")

    def on_submit(event=None):
        password = password_entry.get()
        if password == 'admin123':
            root.quit()
            os._exit(0)
        else:
            messagebox.showerror("错误", "密码错误")

    tk.Label(root, text="请输入密码:", bg='#add8e6', fg='black').pack(pady=10)
    password_entry = tk.Entry(root, show='*')
    password_entry.pack(pady=5)
    tk.Button(root, text="确定", command=on_submit).pack(pady=20)
    root.bind('<Return>', on_submit)
    root.mainloop()
    return False


def on_quit(icon, item):
    quit_program()
    icon.stop()


def on_open_folder(icon, item):
    open_wallpaper_folder()


def create_image():
    try:
        icon_image = Image.open(resource_path('图标/favicon.ico'))
    except FileNotFoundError:
        icon_image = Image.new('RGBA', (64, 64))
        draw = ImageDraw.Draw(icon_image)
        draw.rectangle((0, 0, 64, 64), fill="blue")
        draw.text((10, 10), "A", fill="white")
    return icon_image


def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


def monitor_wallpaper_folder():
    global wallpaper_folder
    wallpaper_folder_abs = os.path.abspath(wallpaper_folder)
    print(f"监视路径: {wallpaper_folder_abs}")
    while True:
        if not os.path.exists(wallpaper_folder_abs):
            print(f"壁纸文件夹 '{wallpaper_folder_abs}' 不存在")
            time.sleep(60)
            continue
        image_files = [f for f in os.listdir(wallpaper_folder_abs) if
                       os.path.isfile(os.path.join(wallpaper_folder_abs, f))]
        if not image_files:
            print(f"壁纸文件夹 '{wallpaper_folder_abs}' 中没有图片")
            time.sleep(60)
            continue
        for image_file in image_files:
            image_file_path = os.path.join(wallpaper_folder_abs, image_file)
            abs_image_path = os.path.abspath(image_file_path)
            set_wallpaper(abs_image_path)
            time.sleep(60)


def setup_tray_icon(icon):
    icon.icon = create_image()
    icon.menu = pystray.Menu(
        pystray.MenuItem("打开壁纸文件夹", on_open_folder),
        pystray.MenuItem("退出", on_quit)
    )
    icon.visible = True


def show_running_alert():
    root = tk.Tk()
    root.title("程序已在运行")
    root.geometry("300x150")
    root.attributes('-alpha', 0.8)
    root.configure(bg='#ffcccc')

    tk.Label(root, text="程序已经在运行!", bg='#ffcccc', fg='black').pack(pady=50)
    tk.Button(root, text="关闭", command=root.destroy).pack(pady=10)

    root.mainloop()


if __name__ == "__main__":
    lock_file = 'wallpaper_changer.lock'
    lock = FileLock(lock_file)
    try:
        with lock.acquire(timeout=10):
            script_dir = os.path.dirname(os.path.abspath(__file__))
            wallpaper_folder = os.path.join(script_dir, "壁纸")
            import pystray

            tray_icon = pystray.Icon("wallpaper_changer")
            tray_thread = threading.Thread(target=tray_icon.run, args=(setup_tray_icon,))
            tray_thread.start()
            monitor_wallpaper_folder()
    except Timeout:
        show_running_alert()
